package com.qsl.rabbit.listener;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author: 青石路
 */
@Component
@Slf4j
public class RabbitConsumerListener {

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue("com.qsl.test.queue"),
            exchange = @Exchange(value = "com.qsl.test.exchange"),
            key = "com.qsl.test.queue")
    )
    public void handleTest(Message message, Channel channel) {
        String content = new String(message.getBody(), StandardCharsets.UTF_8);
        log.info("接收到test消息：{}", content);
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (IOException e) {
            log.error("消息确认失败，异常：", e);
        }
    }

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue("com.qsl.task.queue"),
            exchange = @Exchange(value = "com.qsl.task.exchange"),
            key = "com.qsl.task.queue"),
            ackMode = "AUTO"
    )
    public void handleTask(String msg) {
        log.info("接收到task消息：{}", msg);
    }
}
